import csv
import json
import random
import re

import requests

headers = {
    "User-Agent": "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.83 Safari/537.36"
}

# class SaleParams:
#     """
#     qYear - 当前年份
#     qMonth - 当前月份
#     type - 1=品牌,2=从属品牌,3=车系
#     num - 从当前年月往前推几月,最大十二月
#     typeId - 类型Id
#     """
#
#     def __init__(self, qYear, qMonth, type, num, typeId):
#         self.qYear = qYear
#         self.qMonth = qMonth
#         self.type = type
#         self.num = num
#         self.typeId = typeId
#
#     def get(self):
#         return {
#             "qYear":self.qYear,
#             "qMonth":self.qMonth,
#             "type":self.type,
#             "num":self.num,
#             "typeId":self.typeId,
#         }
#
#
# param = SaleParams(2021, 9, 3, 12, 1933)
# print(param.get())


with open("data/series.txt", "r", encoding="utf-8") as lines:
    for line in lines:
        # 模拟浏览器
        headers["X-Forwarded-For"] = "%s.%s.%s.%s" % (
            random.randrange(1, 200, 20), random.randrange(1, 200, 20), random.randrange(1, 200, 20),
            random.randrange(1, 200, 20))  # IP地址构造

        print(line.split(",")[0])
        url = 'https://price.pcauto.com.cn/price/api/v1/salesCars/getSalesCounter'
        param = {
            "qYear": 2021,
            "qMonth": 9,
            "type": 3,
            "num": 12,
            "typeId": line.split(",")[0].split("sg")[1],
        }
        try:
            ret = requests.get(url=url, headers=headers, params=param).json()  # 发送请求
            ret["seriesId"] = line.split(",")[0]
            print(ret)
            with open("data/last_12m_sale_series.json", 'a', encoding='gbk') as f:
                f.write(json.dumps(ret)+",")
        except:
            pass
